package com.cskaoyan.realm;

import com.cskaoyan.bean.User;
import com.cskaoyan.bean.UserExample;
import com.cskaoyan.bean.UserInfoBean;
import com.cskaoyan.mapper.UserMapper;
import com.cskaoyan.token.WechatToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

//微信直接登录
@Component
public class WechatLoginRealm extends AuthenticatingRealm {

    @Autowired
    UserMapper userMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        WechatToken wechatToken = (WechatToken) authenticationToken;
        UserInfoBean userInfoBean = wechatToken.getUserInfoBean();
        UserExample example = new UserExample();
        String weixinOpenid = (String) wechatToken.getPrincipal();
        example.createCriteria().andWeixinOpenidEqualTo(weixinOpenid);
        List<User> users = userMapper.selectByExample(example);
        if (users != null && users.size() != 0) {
            User user = new User(userInfoBean,weixinOpenid);
            //user.setWeixinOpenid(weixinOpenid);
            userMapper.updateByExampleSelective(user, example);

        } else {
            User user = new User(userInfoBean,weixinOpenid);
            userMapper.insertSelective(user);
            //return new SimpleAuthenticationInfo(userInfoBean,)
        }
        return new SimpleAuthenticationInfo(userInfoBean, weixinOpenid, this.getName());
    }
}
